layui.define(['layer'], function (exports) {
  var $ = layui.$
    , layer = layui.layer;
  var userVo; //当前用户
  var mainAction = {
    /**ajaxPost 提交数据 */
    post: function (url, param, callBackFunc, showLoading) {
      frmAction.ajax(url, 'post', param, 'json', callBackFunc, true, showLoading);
    },
    /** put 提交数据 */
    put: function (url, param, callBackFunc, showLoading) {
      if (showLoading == undefined)
        showLoading = false;
      frmAction.ajax(url, 'put', param, 'json', callBackFunc, true, showLoading);
    },
    /** put 提交数据 */
    delete: function (url, param, callBackFunc, showLoading) {
      if (showLoading == undefined)
        showLoading = false;
      frmAction.ajax(url, 'delete', param, 'json', callBackFunc, true, showLoading);
    },
    /**ajaxGet 提交数据 */
    get: function (url, param, callBackFunc, showLoading) {
      frmAction.ajax(url, 'get', param, 'json', callBackFunc, true, showLoading);
    },
    /**ajax async（同步）提交数据 */
    async: function (url, param, callBackFunc, showLoading) {
      var method = "get";
      if (param["method"] != undefined && param["method"] != "")
        method = param["method"];
      frmAction.ajax(url, method, param, 'json', callBackFunc, false, showLoading);
    }
    ,/**错误msg提示 */
    errorMsg: function (text) {
      top.layer.msg(text, { icon: 2, time: 2000 });
    },
    /**成功 msg提示 */
    successMsg: function (text) {
      top.layer.msg(text, { icon: 1, time: 2000 });
    },
    /**成功 msg提示 */
    warnMsg: function (text) {
      top.layer.msg(text, { icon: 0, time: 2000 });
    },
    /**弹出确定取消的对话框 */
    confirm: function (title, text, callBackFunc) {
      layer.confirm(text, {
        title: title, resize: false,
        btn: ['确定', '取消'],
        btnAlign: '',
        anim: 1,
        icon: 3
      }, callBackFunc, function () { });
    }
    , formatDecimal: function (number, decimals, dec_point, thousands_sep) { //数字格式化，强制要求2位小数，有千分位隔开，格式化后变成“字符串”
      /*
      * 参数说明：
      * number：要格式化的数字
      * decimals：保留几位小数
      * dec_point：小数点符号
      * thousands_sep：千分位符号
      * */
      number = (number + '').replace(/[^0-9+-Ee.]/g, '');
      var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 2 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
          var k = Math.pow(10, prec);
          return LayNumberDiv(LayNumberMul(n, k), k).toFixed(prec);
        };
      s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
      var re = /(-?\d+)(\d{3})/;
      while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
      }

      if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
      }
      return s.join(dec);
    }
    , formatDecimalNum: function (num) {//数字格式化，强制要求2位小数，没有千分位分隔符，格式化后还是数字
      if (num == undefined || num == "" || num == null)
        return Number(0).toFixed(2);
      num = num.toString().replace(/\$|\,/g, '');
      if (isNaN(num))
        return Number(0).toFixed(2);
      return Number(num).toFixed(2);
    }
    , getCurrentDate: function () { // 获取当前时间，返回格式：YYYY-MM-DD
      var day = new Date();
      day.setTime(day.getTime());
      var month = (day.getMonth() + 1) < 10 ? "0" + (day.getMonth() + 1) : (day.getMonth() + 1);
      var date = day.getDate() < 10 ? "0" + day.getDate() : day.getDate();
      var dateStr = day.getFullYear() + "-" + month + "-" + date;
      return dateStr;
    }
    , getUser: function () { //同步获取登录会话信息
      if (userVo) {
        return userVo;
      }
      frmAction.ajax(layui.cache['contentPath'] + '/sys-user/getCurrentUserInfo', 'post', '', 'json', function (result) {
        if (result.code == 0) userVo = result.data;
      }, false);
      return userVo;
    }
  };

  /* 内部函数，不公开 */
  var frmAction = {
    ajax: function (url, method, param, contextType, callBackFunc, async, showLoading) {
      if (showLoading == undefined) { showLoading = true; };
      var lodingIndex = 0;
      if (showLoading) {
        lodingIndex = frmAction.showLoading("加载中，请稍后...");
        if (!url) { layer.close(lodingIndex); return; }
      }
      method = method || 'get';
      if (method != "get" && method != "GET") {
        param = (typeof param == 'string') ? param : JSON.stringify(param);
      }
      $.ajax({
        url: url, type: method, async: async, data: param, dataType: contextType, contentType: "application/json",
        success: function (result) { callBackFunc(result); }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
          if (textStatus == "404") {
            mainAction.errorMsg("请求地址出错!");
          } else if (textStatus == "302") {
            mainAction.errorMsg('连接网页出错!');
          } else if (textStatus == "timeout") {
            mainAction.errorMsg("请求超时!");
          } else {
            mainAction.errorMsg('请求异常!');
          }
        }
        , complete: function (XMLHttpRequest, textStatus) {
          //关闭加载层
          if (showLoading) { frmAction.closeLoading(lodingIndex); }
        }
      });
    }
    , showLoading: function (msg) {
      /** 显示loading加载框 */
      if (msg == undefined || msg == "")
        mst = "数据查询中，请稍候...";
      return layer.msg(msg, { icon: 16, time: false, shade: 0.1 });
    },
    /** 关闭loading框 */
    closeLoading: function (index) {
      layer.close(index);
    }
  };

  /* 表单验证-输入数字后保留2位小数,ele=this,min最小值,max最大值，max最大值,percition:精度，0=整数，其他值 = 小数位 */
  window.LayNumber = function (ele, min, max, percition) {
    var val = $(ele).val();
    if (min == undefined) { min = 0; }
    if (max == undefined) { max = 999999999999; }
    if (percition == undefined || Number(percition) < 0) {
      percition = 0;
    }
    if (val == '' || isNaN(val)) {
      $(ele).val(min);
      return false;
    }
    if (Number(val) < Number(min)) val = min;
    if (Number(val) > Number(max)) val = max;
    if (percition && percition <= 0) {
      $(ele).val(parseInt(val));
    } else {
      $(ele).val(Number(val).toFixed(percition));
    }
    return false;
  };


  // 加法函数
  window.LayNumberAdd = function (arg1, arg2) {
    var t1 = 0, t2 = 0, m;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      t1 = 0;
    }
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      t2 = 0;
    }
    with (Math) {
      m = Math.pow(10, Math.max(t1, t2));
      return ((arg1 * m + arg2 * m) / m).toFixed(2);
    }
  };

  // 减法函数
  window.LayNumberSub = function (arg1, arg2) {
    var t1 = 0, t2 = 0, m, n;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      t1 = 0;
    }
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      t2 = 0;
    }
    with (Math) {
      // 动态控制精度长度
      n = Math.max(t1, t2);
      m = Math.pow(10, n);
      return ((arg1 * m - arg2 * m) / m).toFixed(2);
    }
  };

  // 乘法函数
  window.LayNumberMul = function (arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      t1 = 0;
    }
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      t2 = 0;
    }
    with (Math) {
      r1 = Number(arg1.toString().replace(".", ""));
      r2 = Number(arg2.toString().replace(".", ""));
      return (r1 * r2) / pow(10, t2 + t1);
    }
  };

  // 除法函数
  window.LayNumberDiv = function (arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2, n;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      t1 = 0;
    }
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      t2 = 0;
    }
    with (Math) {
      r1 = Number(arg1.toString().replace(".", ""));
      r2 = Number(arg2.toString().replace(".", ""));
      n = Math.max(t1, t2);
      return (r1 / r2) * pow(10, t2 - t1);
    }
  };
  exports('fsoft', mainAction);
});